package com.wzf.greattruth.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
 * 
 * @Type HessianUtils
 * @Desc
 * @author wuzhengfei
 * @date 2017年10月18日
 * @Version V1.0
 */
public class HessianUtils {
    private final static Logger logger = LoggerFactory.getLogger(HessianUtils.class);

    public static byte[] encode(Object obj) {
        byte[] result = null;
        ByteArrayOutputStream byteOutputStream = null;
        ObjectOutputStream objectOutputStream = null;

        try {
            byteOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteOutputStream);

            objectOutputStream.writeObject(obj);
            objectOutputStream.flush();
            result = byteOutputStream.toByteArray();
        } catch (Exception e) {
            logger.error("encode Exception!  obj={}", JSON.toJSONString(obj) ,e);
        } finally {
            if (null != objectOutputStream) {
                try {
                    objectOutputStream.close();
                } catch (Exception e) {
                    logger.error("encode close ObjectOutputStream Exception!  obj={}", JSON.toJSONString(obj) ,e);
                }
            }
            if (null != byteOutputStream) {
                try {
                    byteOutputStream.close();
                } catch (Exception e) {
                    logger.error("encode close byteOutputStream Exception!  obj={}", JSON.toJSONString(obj) ,e);
                }
            }
        }

        return result;
    }

    @SuppressWarnings("unchecked")
    public static <T> T decode(byte[] bytes) {
        Object result = null;
        ByteArrayInputStream byteInputStream = null;
        ObjectInputStream objectInputStream = null;
        
        try{
            byteInputStream = new ByteArrayInputStream(bytes);
            objectInputStream = new ObjectInputStream(byteInputStream);
            result = objectInputStream.readObject();
        }catch(Exception e){
            logger.error("decode Exception!" ,e);
        }finally {
            if(null != objectInputStream){
                try{
                    objectInputStream.close();
                }catch(Exception e){
                    logger.error("decode close objectInputStream Exception!  obj={}", JSON.toJSONString(result) ,e);
                }
            }
            if(null != byteInputStream){
                try{
                    byteInputStream.close();
                }catch(Exception e){
                    logger.error("decode close byteInputStream Exception!  obj={}", JSON.toJSONString(result) ,e);
                }
            }
        }
        return (T) result;
    }
}